import EditableTable, { IColumns } from '@inbiz/basic/EditableTable';
import { Input, Select } from 'antd';
import { forwardRef, useCallback, useImperativeHandle, useMemo, useRef, useState } from 'react';
const { Option, OptGroup } = Select;
import { TextWidget, getMessage } from '@inbiz/react';
import './index.less';

const IconSettings = (props: any, ref: any) => {
  const { value, fieldsOption, type, isInput } = props;
  const [iconType, $iconType] = useState(
    value?.IconsSettings?.type ?? (value?.IconsSettings?.field ? 'node' : 'normal'),
  );
  const [IconsSettings] = useState(
    (value?.IconsSettings?.field ? [] : value?.IconsSettings?.config) || [],
  );
  const [IconsSettings1] = useState((iconType == 'node' ? value?.IconsSettings.config : []) || []);
  const [field, $field] = useState(
    (value?.IconsSettings?.field ? value.IconsSettings.field : fieldsOption[0]?.options[0].value) ||
      '',
  );
  const iconOption = useMemo(() => {
    return type == 'treeSelect'
      ? [
          {
            label: getMessage('Tree.defaultIcon'),
            value: 'defaultIcon',
          },
          {
            label: getMessage('Tree.topIcon'),
            value: 'topIcon',
          },
        ]
      : [
          {
            label: getMessage('Tree.defaultIcon'),
            value: 'defaultIcon',
          },
          {
            label: getMessage('Tree.expandIcon'),
            value: 'expandIcon',
          },
          {
            label: getMessage('Tree.topIcon'),
            value: 'topIcon',
          },
        ];
  }, []);

  const getRef = () => {
    return useRef<{
      // 获取数据， 会触发校验
      getData: () => Promise<Object>;
      // 主动校验
      valid: () => Promise<Object>;
      // 更新内部数据
      updateSource: (id: string, data: object) => boolean;
    }>();
  };
  const iconTableRef = getRef();

  const getValue = async () => {
    const newIconData = await iconTableRef.current?.getData();
    if (iconType == 'node') {
      return {
        type: 'node',
        field: field,
        config: newIconData,
      };
    } else {
      return {
        type: 'normal',
        config: newIconData,
      };
    }
  };

  useImperativeHandle(ref, () => {
    return {
      getValue,
    };
  });

  const iconColumns: IColumns = useMemo(() => {
    return iconType == 'normal'
      ? [
          {
            title: getMessage('Tree.iconType'),
            dataIndex: 'iconType',
            isIdentical: true,
            width: 150,
            editData: {
              type: 'Select',
              options: iconOption.map((item, index) => {
                return item;
              }),
              rules: [
                {
                  required: true,
                },
              ],
            },

            render: (val, row, index) => {
              return iconOption.filter((item) => item.value == val)[0]?.label || '';
            },
          },
          {
            title: getMessage('Tree.icon'),
            dataIndex: 'iconImg',
            width: 200,
            editData: {
              type: 'IconPicker',
            },
          },
        ]
      : type == 'treeSelect'
      ? [
          {
            title: getMessage('Tree.iconType'),
            dataIndex: 'iconTypeKey',
            isIdentical: true,
            width: 150,
            editData: {
              type: 'Input',
              rules: [
                {
                  required: true,
                },
              ],
            },
          },
          {
            title: getMessage('Tree.defaultIcon'),
            dataIndex: 'defaultIcon',
            width: 200,
            editData: {
              type: 'IconPicker',
            },
            // render: (val, row, index) => {
            //   return <IconPicker value={val} />;
            // },
          },
        ]
      : [
          {
            title: getMessage('Tree.iconType'),
            dataIndex: 'iconTypeKey',
            isIdentical: true,
            width: 150,
            editData: {
              type: 'Input',
              rules: [
                {
                  required: true,
                },
              ],
            },
          },
          {
            title: getMessage('Tree.defaultIcon'),
            dataIndex: 'defaultIcon',
            width: 200,
            editData: {
              type: 'IconPicker',
            },
            // render: (val, row, index) => {
            //   return <IconPicker value={val} />;
            // },
          },
          {
            title: getMessage('Tree.expandIcon'),
            dataIndex: 'expandIcon',
            width: 200,
            editData: {
              type: 'IconPicker',
            },
            // render: (val, row, index) => {
            //   return <IconPicker value={val} />;
            // },
          },
        ];
  }, [iconType]);

  // 图标添加
  const handleAddIcon = useCallback(() => {
    const key = Date.now();
    return { key, id: key };
  }, []);
  // isInput

  const filedSelect = useMemo(() => {
    if (!isInput) {
      return (
        <Select
        showSearch
        filterOption={(input, option) =>
         (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
       }
       optionLabelProp={'label'}
       defaultValue={field}
       style={{ width: 136 }}
       onChange={(val) => {
         $field(val);
       }}
        >
          {fieldsOption?.map((item) => {
            return (
              <OptGroup label={item.label}>
                {item.options?.map((item1: any) => {
                  return (
                    <Option value={item1.value} key={item1.label} label={item1.label}>
                      {item1.label.indexOf('.') != -1 ? item1.label.split('.')[1] : item1.label}
                    </Option>
                  );
                })}
              </OptGroup>
            );
          })}
        </Select>
      );
    } else {
      return (
        <Input
          style={{ width: 136 }}
          defaultValue={field}
          onChange={(val) => {
            $field(val.target.value);
          }}
        />
      );
    }
  }, [fieldsOption, isInput]);

  return (
    <div className={'tree-iconSetting'}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '24px' }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <div style={{ marginRight: '62px' }}>
            {' '}
            <TextWidget>Tree.iconSettings</TextWidget>{' '}
          </div>
          <Select
            defaultValue={iconType}
            value={iconType}
            style={{ width: 136 }}
            onChange={(val) => {
              if (val == 'normal') {
                $field('');
              } else {
                $field(
                  (value?.IconsSettings?.field
                    ? value.IconsSettings.field
                    : fieldsOption[0]?.options[0].value) || '',
                );
              }
              $iconType(val);
            }}
          >
            <Option value="normal">
              <TextWidget>Tree.universalType</TextWidget>
            </Option>
            <Option value="node">
              <TextWidget>Tree.nodalType</TextWidget>
            </Option>
          </Select>
        </div>
        {iconType == 'node' ? (
          <div style={{ display: 'flex', alignItems: 'center', marginRight: '66px' }}>
            <div style={{ marginRight: '62px' }}>
              <TextWidget>Tree.nodeTypeAttribute</TextWidget>
            </div>
            {filedSelect}
          </div>
        ) : (
          <></>
        )}
      </div>
      <EditableTable
        rowKey={'id'}
        columns={iconColumns}
        dataSource={iconType == 'normal' ? IconsSettings : IconsSettings1}
        deleteBtn={{ children: getMessage('Tree.delete'), danger: true }}
        scroll={{ y: 350 }}
        addBtn={{ children: getMessage('Tree.add'), type: 'primary' }}
        onAdd={handleAddIcon}
        ref={iconTableRef}
      />
    </div>
  );
};

export default forwardRef(IconSettings);
